var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var session = require('express-session');
var app = express();

var multipart = require('connect-multiparty');
app.use(multipart({uploadDir:'./public/images' }));//设置上传文件存放的地址。


//集成mongoose 链接数据库             //启动 mongod --dbpath f:\data\db
var mongoose = require('mongoose');            
mongoose.connect('mongodb://localhost/expressdb')     //连接本地数据库blog testuser:testpass@
var db = mongoose.connection;
// 连接成功
db.on('open', function(){
    console.log('MongoDB Connection Successed');
});
// 连接失败
db.on('error', function(){
    console.log('MongoDB Connection Error');
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser('true'));//括号里要写点东西


// session持久化
var MongoStore = require('connect-mongo')(session);
app.use(session({
    secret: "ccxzmnok", //secret的值建议使用随机字符串
    cookie: {maxAge: 60 * 1000 * 60 * 24 * 14}, //过期时间
    resave: true, // 即使 session 没有被修改，也保存 session 值，默认为 true
    saveUninitialized: true,
    store: new MongoStore({
        mongooseConnection: mongoose.connection //使用已有的数据库连接
    })
}));

app.use(express.static(path.join(__dirname, 'public'))); //http://192.168.6.225:3000/images/nanguo.png 可以访问静态资源
//app.use('/static',express.static(path.join(__dirname, 'public'))); //http://192.168.6.225:3000/static/images/nanguo.png 可以访问静态资源

//引入注册路由
require('./routes/routes')(app)

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

//安装一个模块 body-parser 用来解析post请求的参数
var bodyParser = require('body-parser')
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false}));



//配置nodemon热更新
var debug = require('debug')('my-application'); // debug模块
app.set('port', process.env.PORT || 3000); // 设定监听端口
//启动监听
var server = app.listen(app.get('port'), function() {
  debug('Express server listening on port ' + server.address().port);
});
app.use(function(req, res, next){
    app.locals({});
    next();
}
);

//配置打印日志
if('development' === app.get('env')){
    app.set('showStackError',true)
    app.use(logger(':method :url :status :res[content-length] - :response-time ms'))
    app.locals.pretty = true //格式化代码
    mongoose.set('debug',true)
}


 module.exports = app;
